#!/usr/bin/env python

import os
import sys

import numpy
import tables

from fixed_length import EventStream

if len(sys.argv) < 2:
    msg = "fiber-to-pt.py file.fiber0 [file2.fiber0 [...]]"

if len(sys.argv[1:]) == 1:
    path_out = os.path.basename(sys.argv[1]) + '.h5'
else:
    path_out = 'fiber-to-pt.h5'

data = numpy.zeros((4,4,8,4,64))
win  = numpy.zeros((4,4,8,4))
occ  = numpy.zeros((4,4,8,4))


fpout = tables.openFile(path_out, 'w', 
                        'fixed-length packet data from {}'.format(sys.argv[1]))

ptdata = fpout.createEArray(fpout.root, 'data', shape=(0,) + data.shape,
                            atom=tables.Float32Atom())
ptocc  = fpout.createEArray(fpout.root, 'occ',  shape=(0,) + occ.shape, 
                            atom=tables.Int32Atom())
ptwin  = fpout.createEArray(fpout.root, 'win', shape=(0,) + win.shape,
                            atom=tables.Int32Atom())

evtno = []
for path in sys.argv[1:]:
    es = EventStream(path)

    for k, evt in enumerate(es):        
        evtno.append(evt.evtno)
        for j, wf in enumerate(evt):
            try:
                occ[wf.row][wf.col][wf.chan][wf.iread] += 1
            except IndexError:
                print "Index out of bounds: r=%d, c=%d, ch=%d, w=%d" % \
                    (wf.row, wf.col, wf.chan, wf.win)
                continue 

            win[wf.row][wf.col][wf.chan][wf.iread] = wf.win

            for i, samp in enumerate(wf):
                data[wf.row][wf.col][wf.chan][wf.iread][i] = samp
            
        ptdata.append([data])
        ptocc.append([occ])
        ptwin.append([win])


ptevtno = fpout.createArray(fpout.root, 'evtno', evtno)

fpout.close()

